import {FillApi, GetSaveApi, SaveApi, SchoolCheckShow, ShowApi, UploadApi} from '@/services/School/SchoolApi';
import { ServerMessages } from '@/services/ServerMessages';
import {getYear, getYearMonth, ShowError} from '@/utils/format';
import type { ProColumns } from '@ant-design/pro-components';
import {ActionType, EditableProTable, nanoid, PageContainer, ProForm} from '@ant-design/pro-components';
import {Card, DatePicker, Form, message, Modal, Typography} from 'antd';
import React, {useEffect, useRef, useState} from 'react';
import { history } from 'umi';
import Submitter from '../Common/Submitter';
import moment from "moment";
const locale = undefined;

const { Text } = Typography;



type DataSourceType = {
  id: React.Key;
  yr?: string;
  level?: string;
  topic?: string;
  adopt_leader?: string;
  adopt_sit?: string;
  adopt_date?: string;
};

const defaultData: DataSourceType[] = [
  {
    id: nanoid(),
    yr: undefined,
    level: undefined,
    topic: undefined,
    adopt_leader: undefined,
    adopt_sit: undefined,
    adopt_date: undefined,
  },
];

const columns: ProColumns<DataSourceType>[] = [
  {
    title: '年度',
    dataIndex: 'yr',
    width: '180px',
    formItemProps: () => {
      return {
        rules: [{ required: true, message: '此项为必填项' }],
      };
    },
    renderFormItem: () => <DatePicker locale={locale} picker="year" />,
  },
  {
    title: '研究报告/政策咨询主题',
    dataIndex: 'topic',
    formItemProps: () => {
      return {
        rules: [{ required: true, message: '此项为必填项' }],
      };
    },
  },
  {
    title: '批示领导',
    dataIndex: 'adopt_leader',
    formItemProps: () => {
      return {
        rules: [{ required: true, message: '此项为必填项' }],
      };
    },
  },
  {
    title: '采纳情况',
    dataIndex: 'adopt_sit',
    formItemProps: () => {
      return {
        rules: [{ required: true, message: '此项为必填项' }],
      };
    },
    valueEnum: {
      已采纳: '已采纳',
      未采纳: '未采纳',
    },
  },
  {
    title: '采纳/批示时间',
    dataIndex: 'adopt_date',
    // formItemProps: () => {
    //   return {
    //     rules: [{ required: true, message: '此项为必填项' }],
    //   };
    // },
    renderFormItem: () => <DatePicker locale={locale} picker="month" />,
  },
  {
    title: '操作',
    valueType: 'option',
  },
];

export default () => {
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>(() =>
    defaultData.map((item) => item.id),
  );
  const [dataSource, setDataSource] = useState<DataSourceType[]>(() => defaultData);
  const [editForm] = Form.useForm();
  const download = '5_2_2_1';
  const status_is_show = history.location.query.flag === 'display';
  const status_is_check = history.location.query.id && history.location.query.fill_id;
  const actionRef = useRef<ActionType>();
  const handleSaveBtn = () => {
    console.log("@Save", download)
    const data = {
      fill_id: download,
      data: dataSource
    }
    console.log("@请求数据", data)
    SaveApi('/api/temp-save', data).then(response => {
      if (response.status === 0) {
        Modal.success({
          title: <span>保存成功！</span>,
          onOk() {
            window.location.reload()
          }
        })
      } else {
        ShowError(response.message)
      }
    }, () => {
      ShowError(ServerMessages.error_message)
    })
  }

  const upload = UploadApi(
    '/api/index/social-services/services-social/consultative-nation-counts-template',
    (info) => {
      console.log('@success', info);
      if (info.file.response.status === 0) {
        const data = info.file.response.data["data_"+download]
        for (let i = 0; i < data.length; i++) {
          data[i].id = nanoid()
          data[i].yr = moment(data[i].yr, 'YYYY')
          data[i].adopt_date = moment(data[i].adopt_date, 'YYYY-MM')
        }
        setDataSource(data)
        var id_arr = []
        for (let i = 0; i < data.length; i++) {
          id_arr.push(data[i].id)
        }
        setEditableRowKeys(id_arr)
      } else {
        ShowError(info.file.response.message);
      }
    },
  );

  // 更新
  const [reload, setReload] = useState(false)
  useEffect(() => {
    // 插入
        if (status_is_check) {
          // 审核时加载内容
          SchoolCheckShow(history.location.query.id, history.location.query.fill_id).then(
            (response) => {
              console.log(response);
              if (response.status === 0) {
                for (let i = 0; i < response.message.length; i++) {
                  response.message[i].id = nanoid()
                  // response.message[i].yr = response.message[i].yr ? moment(response.message[i].yr, 'YYYY') : undefined
                  // response.message[i].adopt_date = response.message[i].adopt_date ? moment(response.message[i].adopt_date, 'YYYY-MM') : undefined
                }
                setDataSource(response.message)
                // resolve({data: response.message})
              } else {
                // resolve(true);
              }
            },
          );
        } else if (status_is_show) {
          // 查看时加载内容
          ShowApi(download).then((response) => {
            console.log('@response', response);
            if (response.status === 0) {
              setDataSource(response.data)
              // resolve({ data: response.data });
            }
          });
          // resolve(true)
        } else {
          // resolve({data: dataSource})
          GetSaveApi('/api/show-temp-save', download).then(response => {
            console.log("@response", response)
            if (response.status === 0) {
              for (let i = 0; i < response.data.length; i++) {
                response.data[i].id = nanoid()
                response.data[i].yr = response.data[i].yr ? moment(response.data[i].yr, 'YYYY') : undefined
                response.data[i].adopt_date = response.data[i].adopt_date ? moment(response.data[i].adopt_date, 'YYYY-MM') : undefined
              }
              setDataSource(response.data);
              var id_arr = []
              for (let i = 0; i < response.data.length; i++) {
                id_arr.push(response.data[i].id)
              }
              setEditableRowKeys(id_arr)
            } else {
              setDataSource(dataSource)
              // resolve({data: dataSource})
            }
          })
        }
    console.log("@update", actionRef.current, dataSource)
  }, [reload])

  // useEffect(() => {
  //   console.log("@editable", dataSource)
  //   for (let i = 0; i < dataSource.length; i++) {
  //     actionRef.current.startEditable(dataSource[i].id);
  //   }
  // }, [dataSource])

  return (
    <PageContainer
      title="国家级咨政研究情况"
      content={
        <Typography.Text type="danger">
          1. 监测点内涵：2021年1月1日至今，学科获国家领导人肯定性批示数量及清单。
          <br />
          2. 采纳情况：采纳、未采纳。
          <br />
          3. 采纳/批示时间：请用"YYYY-MM"格式填报。若未采纳，则采纳/批示时间为空。
          <br />
          4. 年度：请用"YYYY"格式填报。
          <br/>5. 仅填写当前填报周期内新增的数据，如有删减，请告知学校管理员。
        </Typography.Text>
      }
    >
      <Card bordered={false}>
        <ProForm
          onFinish={async () => {
            if (dataSource.length === 0) {
              message.warn("请输入内容")
              return {}
            }
            return new Promise((resolve) => {
              editForm.validateFields().then(
                () => {
                  for (let i = 0; i < dataSource.length; i++) {
                    dataSource[i].yr = getYear(dataSource[i].yr);
                    dataSource[i].adopt_date = getYearMonth(dataSource[i].adopt_date);
                  }

                  const dataObj = {
                    data_5_2_2_1: dataSource,
                  };
                  console.log('@请求数据', dataObj);

                  FillApi(
                    '/api/index/social-services/services-social/consultative-nation-counts',
                    dataObj,
                    (response) => {
                      message.success(response.message);
                      history.push('/social-services/social-support');
                      resolve(true);
                    },
                    (response) => {
                      ShowError(response.message);
                      resolve(false);
                    },
                    () => {
                      ShowError(ServerMessages.error_message);
                      resolve(false);
                    },
                  );
                },
                () => {
                  resolve(false);
                },
              );
            });
          }}
          submitter={{
            render: (props, doms) => {
              return <Submitter upload={upload} download={download} doms={doms} save={handleSaveBtn}/>;
            },
            resetButtonProps: {
              style: {
                // 隐藏重置按钮
                display: 'none',
              },
            },
            submitButtonProps: {
              style: {
                marginLeft: '-8px',
              },
            },
          }}
        >
          <EditableProTable<DataSourceType>
            pagination={{
              pageSize: 10
            }}
            value={dataSource}
            onChange={setDataSource}
            actionRef={actionRef}
            // request={async () => {
            //   // 如果是审核或者查看,则异步加载内容
            //   return new Promise((resolve) => {
            //     if (status_is_check) {
            //       // 审核时加载内容
            //       SchoolCheckShow(history.location.query.id, history.location.query.fill_id).then(
            //         (response) => {
            //           console.log(response);
            //           if (response.status === 0) {
            //             resolve({data: response.message})
            //           } else {
            //             resolve(true);
            //           }
            //         },
            //       );
            //     } else if (status_is_show) {
            //       // 查看时加载内容
            //       ShowApi(download).then((response) => {
            //         console.log('@response', response);
            //         if (response.status === 0) {
            //           resolve({ data: response.data });
            //         }
            //       });
            //       // resolve(true)
            //     } else {
            //       // resolve({data: dataSource})
            //       GetSaveApi('/api/show-temp-save', download).then(response => {
            //         console.log("@response", response)
            //         if (response.status === 0) {
            //           for (let i = 0; i < response.data.length; i++) {
            //             response.data[i].id = nanoid()
            //             response.data[i].yr = response.data[i].yr ? moment(response.data[i].yr, 'YYYY') : undefined
            //             response.data[i].adopt_date = response.data[i].adopt_date ? moment(response.data[i].adopt_date, 'YYYY-MM') : undefined
            //           }
            //           resolve({data: response.data})
            //           for (let i = 0; i < response.data.length; i++) {
            //             actionRef.current.startEditable(response.data[i].id)
            //           }
            //           setDataSource(response.data)
            //         } else {
            //           resolve({data: dataSource})
            //         }
            //       })
            //     }
            //   });
            // }}
            columns={columns}
            rowKey="id"
            recordCreatorProps={{
              newRecordType: 'dataSource',
              record: () => ({
                id: nanoid(),
              }),
              style: {
                display: status_is_show || status_is_check ? 'none' : 'block',
              },
            }}
            editable={{
              type: 'multiple',
              form: editForm,
              editableKeys,
              actionRender: (row, config, defaultDoms) => {
                return [defaultDoms.delete];
              },
              onValuesChange: (record, recordList) => {
                if (record) {
                  setDataSource(recordList);
                } else {
                  // recordList 代表表单的真实数据，但是在空值检测时会变成空值，
                  // 所以只在有输入变化时同步到 DataSource，可以通过 record 来判断是否有输入。
                  // 执行删除操作时，DataSource 应该删掉 recordList 中不存在的项目。
                  let index_list = []
                  for (let i = 0; i < recordList.length; i++) {
                    index_list.push(recordList[i].id)
                  }
                  let newDataSource = []
                  for (let i = 0; i < dataSource.length; i++) {
                    if (index_list.indexOf(dataSource[i].id) !== -1) {
                      newDataSource.push(dataSource[i])
                    }
                  }
                  setDataSource(newDataSource)
                }
              },
              onChange: setEditableRowKeys,
            }}
            style={{ marginBottom: 20 }}
          />
        </ProForm>
      </Card>
    </PageContainer>
  );
};
